<template>
  <div class="schedule-management">
    <!-- 页面加载状态 -->
    <div v-if="pageLoading" class="loading-container" v-loading="true" element-loading-text="正在加载课程表数据...">
      <div style="height: 400px;"></div>
    </div>

    <!-- 主要内容 -->
    <el-card v-else class="box-card">
      <template #header>
        <div class="card-header">
          <span>课程表管理 
            <span v-if="filterForm.weekNumber" class="header-info">
              - {{ filterForm.academicYear }} {{ filterForm.semester }} 第{{ filterForm.weekNumber }}周
              <span v-if="filterForm.classId">
                ({{ getSelectedClassName() }})
              </span>
              <span v-else>(所有班级)</span>
            </span>
          </span>
          <div class="header-controls">
            <el-button type="primary" @click="showQuickAdd = true" :disabled="!filterForm.semester">快速添加</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="学年">
            <el-select v-model="filterForm.academicYear" placeholder="选择学年" @change="onFilterChange" style="width: 150px;">
              <el-option label="2024-2025" value="2024-2025"></el-option>
              <el-option label="2023-2024" value="2023-2024"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学期">
            <el-select v-model="filterForm.semester" placeholder="选择学期" @change="onFilterChange" style="width: 120px;">
              <el-option label="第一学期" value="第一学期"></el-option>
              <el-option label="第二学期" value="第二学期"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级">
            <el-select v-model="filterForm.classId" placeholder="选择班级" @change="onFilterChange" clearable style="width: 200px;">
              <el-option label="所有班级" :value="null"></el-option>
              <el-option 
                v-for="clazz in teacherClasses" 
                :key="clazz.id"
                :label="clazz.name" 
                :value="clazz.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="周次">
            <el-select v-model="filterForm.weekNumber" placeholder="选择周次" @change="onFilterChange" style="width: 120px;">
              <el-option 
                v-for="week in 20" 
                :key="week" 
                :label="`第${week}周`" 
                :value="week">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        
        <!-- 班级颜色图例 -->
        <div v-if="filterForm.classId === null && teacherClasses.length > 0" class="class-legend">
          <div class="legend-title">班级颜色图例：</div>
          <div class="legend-items">
            <div 
              v-for="clazz in teacherClasses" 
              :key="clazz.id"
              class="legend-item">
              <div 
                class="legend-color" 
                :style="{ backgroundColor: getClassColor(clazz.id) }">
              </div>
              <span class="legend-text">{{ clazz.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 课程表网格 -->
      <div class="schedule-grid-container" v-if="filterForm.weekNumber">
        <div class="schedule-grid">
          <!-- 表头 -->
          <div class="grid-header">
            <div class="time-header">时间</div>
            <div class="day-header" v-for="day in weekDays" :key="day.value">
              {{ day.label }}
            </div>
          </div>

          <!-- 时间行 -->
          <div 
            v-for="timeSlot in timeSlots" 
            :key="timeSlot.timeSlot" 
            class="grid-row">
            
            <!-- 时间列 -->
            <div class="time-cell">
              <div class="time-slot-name">{{ timeSlot.slotName }}</div>
              <div class="time-range">{{ timeSlot.startTime }}-{{ timeSlot.endTime }}</div>
              <div class="time-period">{{ timeSlot.period }}</div>
            </div>

            <!-- 课程格子 -->
            <div 
              v-for="day in weekDays" 
              :key="`${timeSlot.timeSlot}-${day.value}`"
              class="course-cell"
              :class="{ 
                'has-course': filterForm.classId ? getCellCourse(timeSlot.timeSlot, day.value) : getCellCourses(timeSlot.timeSlot, day.value).length > 0,
                'has-other-class': filterForm.classId && hasOtherClassCourse(timeSlot.timeSlot, day.value),
                'disabled': filterForm.classId && hasOtherClassCourse(timeSlot.timeSlot, day.value),
                'drag-over': isDragging
              }"
              @click="handleCellClick(timeSlot.timeSlot, day.value)"
              @dragover.prevent="handleDragOver"
              @drop="handleDrop($event, timeSlot.timeSlot, day.value)">
              
              <!-- 选择特定班级时显示单个课程 -->
              <div v-if="filterForm.classId && getCellCourse(timeSlot.timeSlot, day.value)" 
                   class="course-content"
                   :class="{ 'other-teacher-course': !isCurrentUserCourse(getCellCourse(timeSlot.timeSlot, day.value)) }"
                   :draggable="isCurrentUserCourse(getCellCourse(timeSlot.timeSlot, day.value))"
                   @dragstart="handleDragStart($event, getCellCourse(timeSlot.timeSlot, day.value))"
                   @dragend="handleDragEnd"
                   @click.stop="viewCourseDetails(getCellCourse(timeSlot.timeSlot, day.value))">
                <div class="course-name">{{ getCellCourse(timeSlot.timeSlot, day.value).courseName }}</div>
                <div class="course-time">{{ getDetailedTimeDisplay(timeSlot.timeSlot) }}</div>
                <div class="course-teacher">{{ getCellCourse(timeSlot.timeSlot, day.value).teacherName }}</div>
                <div v-if="getCellCourse(timeSlot.timeSlot, day.value).className" class="course-class">{{ getCellCourse(timeSlot.timeSlot, day.value).className }}</div>
                
                <!-- 只有自己的课程才显示操作按钮 -->
                <div v-if="isCurrentUserCourse(getCellCourse(timeSlot.timeSlot, day.value))" class="course-actions">
                  <el-button type="text" size="small" @click.stop="editCourse(getCellCourse(timeSlot.timeSlot, day.value))">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="text" size="small" @click.stop="removeCourse(getCellCourse(timeSlot.timeSlot, day.value))">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                
                <!-- 只有自己的课程才显示拖拽手柄 -->
                <div v-if="isCurrentUserCourse(getCellCourse(timeSlot.timeSlot, day.value))" class="drag-handle">⋮⋮</div>
                
                <!-- 其他教师的课程显示只读标识 -->
                <div v-if="!isCurrentUserCourse(getCellCourse(timeSlot.timeSlot, day.value))" class="readonly-indicator">
                  <el-icon><Lock /></el-icon>
                </div>
              </div>

              <!-- 选择特定班级时，显示其他班级的课程（淡化显示） -->
              <div v-else-if="filterForm.classId && hasOtherClassCourse(timeSlot.timeSlot, day.value)" class="other-class-content">
                <div 
                  v-for="course in getOtherClassCourses(timeSlot.timeSlot, day.value)" 
                  :key="course.id"
                  class="other-course-item"
                  :style="{ backgroundColor: getClassColor(course.classId) }">
                  <div class="course-name">{{ course.courseName }}</div>
                  <div class="course-class">{{ course.className }}</div>
                  <div class="course-teacher">{{ course.teacherName }}</div>
                </div>
                <div class="disabled-overlay">
                  <div class="disabled-text">时间冲突</div>
                </div>
              </div>

              <!-- 选择所有班级时显示多个课程 -->
              <div v-else-if="!filterForm.classId && getCellCourses(timeSlot.timeSlot, day.value).length > 0" class="multiple-courses">
                <div 
                  v-for="course in getCellCourses(timeSlot.timeSlot, day.value)" 
                  :key="course.id"
                  class="course-item"
                  :class="{ 'other-teacher-course': !isCurrentUserCourse(course) }"
                  :style="{ backgroundColor: getClassColor(course.classId) }"
                  :draggable="isCurrentUserCourse(course)"
                  @dragstart="handleDragStart($event, course)"
                  @dragend="handleDragEnd"
                  @click.stop="viewCourseDetails(course)">
                  <div class="course-name">{{ course.courseName }}</div>
                  <div class="course-class">{{ course.className }}</div>
                  <div class="course-teacher">{{ course.teacherName }}</div>
                  
                  <!-- 只有自己的课程才显示操作按钮 -->
                  <div v-if="isCurrentUserCourse(course)" class="course-actions">
                    <el-button type="text" size="small" @click.stop="editCourse(course)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="text" size="small" @click.stop="removeCourse(course)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  
                  <!-- 只有自己的课程才显示拖拽手柄 -->
                  <div v-if="isCurrentUserCourse(course)" class="drag-handle">⋮⋮</div>
                  
                  <!-- 其他教师的课程显示只读标识 -->
                  <div v-if="!isCurrentUserCourse(course)" class="readonly-indicator">
                    <el-icon><Lock /></el-icon>
                  </div>
                </div>
              </div>

              <!-- 无课程时显示 -->
              <div v-else class="empty-content">
                <div class="add-hint">点击添加课程</div>
                <div v-if="isDragging" class="drop-hint">拖拽到此处</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 提示信息 -->
      <div class="no-week-selected" v-else>
        <el-empty description="请选择周次查看课程表">
          <el-button type="primary" @click="filterForm.weekNumber = 1">查看第1周</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 添加课程对话框 -->
    <el-dialog v-model="showAddDialog" title="添加课程" width="450px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
        <el-form-item label="学年">
          <el-input :value="filterForm.academicYear" readonly />
        </el-form-item>
        <el-form-item label="学期">
          <el-input :value="filterForm.semester" readonly />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="addForm.courseId" placeholder="请选择课程" style="width: 100%">
            <el-option 
              v-for="course in availableCourses" 
              :key="course.value"
              :label="course.label" 
              :value="course.value">
            </el-option>
          </el-select>
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            共找到 {{ availableCourses.length }} 门可选课程
          </div>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="addForm.classId" placeholder="请选择班级" style="width: 100%" @change="onClassChange">
            <el-option 
              v-for="clazz in teacherClasses" 
              :key="clazz.id"
              :label="clazz.name" 
              :value="clazz.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="星期">
          <el-input :value="getDayName(addForm.dayOfWeek)" readonly />
        </el-form-item>
        <el-form-item label="时间段">
          <el-input :value="getTimeSlotName(addForm.timeSlot)" readonly />
        </el-form-item>
        <el-form-item label="周次">
          <el-input :value="`第${filterForm.weekNumber}周`" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addSingleCourse" :loading="addLoading">添加课程</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 快速添加课程对话框 -->
    <el-dialog v-model="showQuickAdd" title="快速添加课程" width="500px">
      <el-form :model="quickAddForm" :rules="quickAddRules" ref="quickAddFormRef" label-width="80px">
        <el-form-item label="学年">
          <el-input :value="filterForm.academicYear" readonly />
        </el-form-item>
        <el-form-item label="学期">
          <el-input :value="filterForm.semester" readonly />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="quickAddForm.courseId" placeholder="请选择课程" style="width: 100%">
            <el-option 
              v-for="course in availableCourses" 
              :key="course.value"
              :label="course.label" 
              :value="course.value">
            </el-option>
          </el-select>
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            共找到 {{ availableCourses.length }} 门可选课程
          </div>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="quickAddForm.classId" placeholder="请选择班级" style="width: 100%" @change="onQuickAddClassChange">
            <el-option 
              v-for="clazz in teacherClasses" 
              :key="clazz.id"
              :label="clazz.name" 
              :value="clazz.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周次" prop="weekNumbers">
          <el-select v-model="quickAddForm.weekNumbers" multiple placeholder="请选择周次" style="width: 100%">
            <el-option 
              v-for="week in 20" 
              :key="week" 
              :label="`第${week}周`" 
              :value="week">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="星期" prop="dayOfWeek">
          <el-select v-model="quickAddForm.dayOfWeek" placeholder="请选择星期" style="width: 100%">
            <el-option 
              v-for="day in weekDays" 
              :key="day.value"
              :label="day.label" 
              :value="day.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间段" prop="timeSlot">
          <el-select v-model="quickAddForm.timeSlot" placeholder="请选择时间段" style="width: 100%">
            <el-option 
              v-for="slot in timeSlots" 
              :key="slot.timeSlot"
              :label="`${slot.slotName} (${slot.startTime}-${slot.endTime})`" 
              :value="slot.timeSlot">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showQuickAdd = false">取消</el-button>
          <el-button type="primary" @click="quickAddCourse" :loading="quickAddLoading">批量添加</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑课程对话框 -->
    <el-dialog v-model="showEditDialog" :title="editCourseForm.isReadOnly ? '课程详情（只读）' : '课程详情'" width="400px">
      <el-form :model="editCourseForm" label-width="80px">
        <el-form-item label="课程名称">
          <el-input v-model="editCourseForm.courseName" readonly></el-input>
        </el-form-item>
        <el-form-item label="时间段">
          <el-input :value="getTimeSlotDisplay(editCourseForm.timeSlot)" readonly></el-input>
        </el-form-item>
        <el-form-item label="教师">
          <el-input v-model="editCourseForm.teacherName" readonly></el-input>
        </el-form-item>
        <el-form-item label="班级" v-if="editCourseForm.className">
          <el-input v-model="editCourseForm.className" readonly></el-input>
        </el-form-item>
        <el-form-item v-if="editCourseForm.isReadOnly" label="说明">
          <el-alert 
            title="这是其他教师的课程，您只能查看详情，无法编辑或删除" 
            type="info" 
            :closable="false"
            show-icon>
          </el-alert>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import scheduleApi from '../../api/schedule'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '../../stores/user'

// 响应式数据
const userStore = useUserStore()
const showQuickAdd = ref(false)
const showEditDialog = ref(false)
const showAddDialog = ref(false)
const quickAddLoading = ref(false)
const addLoading = ref(false)
const pageLoading = ref(true)
const currentUserId = computed(() => userStore.currentUser.id)

const filterForm = reactive({
  academicYear: '2024-2025',
  semester: '第一学期',
  weekNumber: null,
  classId: null
})

const quickAddForm = reactive({
  courseId: null,
  classId: null,
  weekNumbers: [],
  dayOfWeek: null,
  timeSlot: null
})

const editCourseForm = reactive({
  id: null,
  courseName: '',
  timeSlot: null,
  teacherName: '',
  className: '',
  isReadOnly: false
})

const addForm = reactive({
  courseId: null,
  classId: null,
  dayOfWeek: null,
  timeSlot: null
})

const quickAddRules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  weekNumbers: [{ required: true, message: '请选择周次', trigger: 'change' }],
  dayOfWeek: [{ required: true, message: '请选择星期', trigger: 'change' }],
  timeSlot: [{ required: true, message: '请选择时间段', trigger: 'change' }]
}

const addRules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }]
}

const weekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

const timeSlots = ref([])
const scheduleData = ref({})
const availableCourses = ref([])
const teacherClasses = ref([])

// 班级颜色映射
const classColors = [
  '#e3f2fd', '#f3e5f5', '#e8f5e8', '#fff3e0', '#fce4ec',
  '#e0f2f1', '#f9fbe7', '#fff8e1', '#f1f8e9', '#e8eaf6'
]

const classColorMap = ref({})

// 拖拽相关
const isDragging = ref(false)
const draggedCourse = ref(null)

// Template refs
const addFormRef = ref(null)
const quickAddFormRef = ref(null)

// 初始化数据
const initializeData = async () => {
  try {
    pageLoading.value = true
    
    await getCurrentUserInfo()
    restoreViewPosition()
    
    await Promise.all([
      loadTimeSlots(),
      loadTeacherClasses(),
      loadAvailableCourses()
    ])
    
    if (!filterForm.weekNumber) {
      filterForm.weekNumber = getCurrentWeek()
    }
    
    await loadSchedule()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败，请刷新页面重试')
  } finally {
    pageLoading.value = false
  }
}

// 获取当前用户信息
const getCurrentUserInfo = async () => {
  try {
    if (userStore.isLoggedIn && userStore.currentUser.id) {
      console.log('当前用户ID:', currentUserId.value)
    } else {
      console.warn('未找到用户信息，可能需要重新登录')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 检查课程是否属于当前用户
const isCurrentUserCourse = (course) => {
  return course && course.teacherId === currentUserId.value
}

// 获取当前周次
const getCurrentWeek = () => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1
  
  let semesterStart
  if (currentMonth >= 9 || currentMonth <= 1) {
    semesterStart = new Date(currentMonth >= 9 ? currentYear : currentYear - 1, 8, 1)
  } else {
    semesterStart = new Date(currentYear, 1, 1)
  }
  
  const timeDiff = now.getTime() - semesterStart.getTime()
  const weekDiff = Math.floor(timeDiff / (7 * 24 * 60 * 60 * 1000)) + 1
  const week = Math.max(1, Math.min(20, weekDiff))
  
  return week
}

// 保存当前查看位置到本地存储
const saveViewPosition = () => {
  const viewPosition = {
    academicYear: filterForm.academicYear,
    semester: filterForm.semester,
    weekNumber: filterForm.weekNumber,
    classId: filterForm.classId,
    timestamp: Date.now()
  }
  localStorage.setItem('scheduleViewPosition', JSON.stringify(viewPosition))
}

// 恢复上次查看的位置
const restoreViewPosition = () => {
  try {
    const saved = localStorage.getItem('scheduleViewPosition')
    if (saved) {
      const viewPosition = JSON.parse(saved)
      const isRecent = Date.now() - viewPosition.timestamp < 24 * 60 * 60 * 1000
      if (isRecent) {
        filterForm.academicYear = viewPosition.academicYear || '2024-2025'
        filterForm.semester = viewPosition.semester || '第一学期'
        filterForm.weekNumber = viewPosition.weekNumber
        filterForm.classId = viewPosition.classId
      }
    }
  } catch (error) {
    console.error('恢复查看位置失败:', error)
  }
}

const loadTimeSlots = async () => {
  try {
    const response = await scheduleApi.getAllTimeSlots()
    if (response.code === 200) {
      timeSlots.value = response.data || []
    }
  } catch (error) {
    console.error('获取时间段失败:', error)
  }
}

const loadTeacherClasses = async () => {
  try {
    const response = await scheduleApi.getTeacherClasses()
    if (response.code === 200) {
      teacherClasses.value = response.data || []
      console.log('教师班级列表:', teacherClasses.value)
      assignClassColors()
    }
  } catch (error) {
    console.error('获取教师班级失败:', error)
    ElMessage.error('获取班级列表失败')
  }
}

// 为班级分配颜色
const assignClassColors = () => {
  classColorMap.value = {}
  teacherClasses.value.forEach((clazz, index) => {
    classColorMap.value[clazz.id] = classColors[index % classColors.length]
  })
}

// 获取班级对应的颜色
const getClassColor = (classId) => {
  return classColorMap.value[classId] || '#e3f2fd'
}

const loadAvailableCourses = async (classId = null) => {
  try {
    if (!filterForm.semester) {
      ElMessage.warning('请先选择学期')
      availableCourses.value = []
      return
    }
    
    let response
    if (classId) {
      response = await scheduleApi.getAvailableCoursesForClass(filterForm.academicYear, filterForm.semester, classId)
    } else {
      response = await scheduleApi.getAvailableCourses(filterForm.academicYear, filterForm.semester)
    }
    
    if (response.code === 200) {
      availableCourses.value = (response.data || []).map(course => ({
        value: course.id,
        label: `${course.courseName} (剩余${course.remainingHours || course.courseHours}课时)`,
        courseName: course.courseName,
        id: course.id,
        remainingHours: course.remainingHours || course.courseHours,
        courseHours: course.courseHours,
        semester: course.semester
      }))
      
      console.log('加载的可用课程:', availableCourses.value)
    }
  } catch (error) {
    console.error('获取可选课程失败:', error)
    ElMessage.error('获取可选课程失败')
  }
}

const loadSchedule = async () => {
  if (!filterForm.weekNumber) return
  
  try {
    const response = await scheduleApi.getWeeklyScheduleByClass(
      filterForm.academicYear, 
      filterForm.weekNumber,
      filterForm.classId
    )
    
    if (response.code === 200) {
      scheduleData.value = response.data || {}
    } else {
      ElMessage.error(response.message || '获取课程表失败')
    }
    
    saveViewPosition()
  } catch (error) {
    console.error('获取课程表失败:', error)
    ElMessage.error('获取课程表失败')
  }
}

const getCellCourse = (timeSlot, dayOfWeek) => {
  const dayKey = String(dayOfWeek)
  const daySchedules = scheduleData.value[dayKey] || []
  return daySchedules.find(s => s.timeSlot === timeSlot)
}

const getCellCourses = (timeSlot, dayOfWeek) => {
  const dayKey = String(dayOfWeek)
  const daySchedules = scheduleData.value[dayKey] || []
  return daySchedules.filter(s => s.timeSlot === timeSlot)
}

const hasOtherClassCourse = (timeSlot, dayOfWeek) => {
  if (!filterForm.classId) return false
  const dayKey = String(dayOfWeek)
  const daySchedules = scheduleData.value[dayKey] || []
  const otherClassCourses = daySchedules.filter(s => s.timeSlot === timeSlot && s.classId !== filterForm.classId)
  return otherClassCourses.length > 0
}

const getOtherClassCourses = (timeSlot, dayOfWeek) => {
  if (!filterForm.classId) return []
  const dayKey = String(dayOfWeek)
  const daySchedules = scheduleData.value[dayKey] || []
  return daySchedules.filter(s => s.timeSlot === timeSlot && s.classId !== filterForm.classId)
}

const handleCellClick = async (timeSlot, dayOfWeek) => {
  if (teacherClasses.value.length === 0) {
    ElMessage.warning('您还没有分配到任何班级，无法添加课程')
    return
  }
  
  console.log('=== 点击单元格 ===')
  console.log('时间段:', timeSlot, '星期:', dayOfWeek)
  
  if (filterForm.classId === null) {
    const existingCourses = getCellCourses(timeSlot, dayOfWeek)
    if (existingCourses.length > 0) {
      ElMessage.warning('该时间段已有课程安排，无法添加新课程')
      return
    }
    addForm.classId = null
  } else {
    if (hasOtherClassCourse(timeSlot, dayOfWeek)) {
      ElMessage.warning('该时间段已有其他班级的课程，无法添加')
      return
    }
    
    const existingCourse = getCellCourse(timeSlot, dayOfWeek)
    if (existingCourse) {
      editCourse(existingCourse)
      return
    }
    addForm.classId = filterForm.classId
  }
  
  addForm.dayOfWeek = dayOfWeek
  addForm.timeSlot = timeSlot
  addForm.courseId = null
  
  console.log('设置表单数据:', {
    dayOfWeek: addForm.dayOfWeek,
    timeSlot: addForm.timeSlot,
    classId: addForm.classId,
    courseId: addForm.courseId
  })
  
  if (addForm.classId) {
    console.log('预加载班级课程，班级ID:', addForm.classId)
    await loadAvailableCourses(addForm.classId)
  } else {
    console.log('预加载所有课程')
    await loadAvailableCourses()
  }
  
  showAddDialog.value = true
  console.log('打开添加对话框')
}

const addSingleCourse = async () => {
  if (!addFormRef.value) return
  
  try {
    console.log('=== 添加课程调试信息 ===')
    console.log('表单数据:', addForm)
    console.log('可用课程列表:', availableCourses.value)
    console.log('选中的课程ID:', addForm.courseId)
    console.log('选中的班级ID:', addForm.classId)
    
    await addFormRef.value.validate()
    
    const conflictResponse = await scheduleApi.checkTimeConflict(
      filterForm.academicYear,
      filterForm.weekNumber,
      addForm.dayOfWeek,
      addForm.timeSlot,
      addForm.classId
    )
    
    if (conflictResponse.code === 200 && conflictResponse.data === true) {
      ElMessage.error('该时间段已有课程安排，无法添加')
      return
    }
    
    addLoading.value = true
    
    const selectedClass = teacherClasses.value.find(c => c.id === addForm.classId)
    const selectedCourse = availableCourses.value.find(c => c.value === addForm.courseId)
    
    console.log('找到的班级:', selectedClass)
    console.log('找到的课程:', selectedCourse)
    
    if (!selectedCourse) {
      ElMessage.error('未找到选中的课程，请重新选择')
      return
    }
    
    if (!selectedClass) {
      ElMessage.error('未找到选中的班级，请重新选择')
      return
    }
    
    const data = {
      courseId: addForm.courseId,
      courseName: selectedCourse.courseName,
      classId: addForm.classId,
      className: selectedClass.name,
      academicYear: filterForm.academicYear,
      semester: filterForm.semester,
      weekNumber: filterForm.weekNumber,
      dayOfWeek: addForm.dayOfWeek,
      timeSlot: addForm.timeSlot,
      reducedHours: 1
    }
    
    console.log('提交的数据:', data)
    
    const response = await scheduleApi.addCourseToSchedule(data)
    if (response.code === 200) {
      ElMessage.success('添加课程成功')
      showAddDialog.value = false
      loadSchedule()
      if (filterForm.classId) {
        loadAvailableCourses(filterForm.classId)
      } else {
        loadAvailableCourses()
      }
    } else {
      ElMessage.error(response.message || '添加课程失败')
    }
  } catch (error) {
    console.error('添加课程失败:', error)
    ElMessage.error(error.message || '添加课程失败')
  } finally {
    addLoading.value = false
  }
}

const quickAddCourse = async () => {
  if (!quickAddFormRef.value) return
  
  try {
    await quickAddFormRef.value.validate()
    
    quickAddLoading.value = true
    
    const selectedClass = teacherClasses.value.find(c => c.id === quickAddForm.classId)
    const selectedCourse = availableCourses.value.find(c => c.value === quickAddForm.courseId)
    
    const promises = quickAddForm.weekNumbers.map(async weekNumber => {
      const conflictResponse = await scheduleApi.checkTimeConflict(
        filterForm.academicYear,
        weekNumber,
        quickAddForm.dayOfWeek,
        quickAddForm.timeSlot,
        quickAddForm.classId
      )
      
      if (conflictResponse.code === 200 && conflictResponse.data === true) {
        throw new Error(`第${weekNumber}周该时间段已有课程安排`)
      }
      
      const data = {
        courseId: quickAddForm.courseId,
        courseName: selectedCourse?.courseName || '',
        classId: quickAddForm.classId,
        className: selectedClass?.name || '',
        academicYear: filterForm.academicYear,
        semester: filterForm.semester,
        weekNumber: weekNumber,
        dayOfWeek: quickAddForm.dayOfWeek,
        timeSlot: quickAddForm.timeSlot,
        reducedHours: 1
      }
      return scheduleApi.addCourseToSchedule(data)
    })
    
    await Promise.all(promises)
    
    ElMessage.success(`成功添加 ${quickAddForm.weekNumbers.length} 个课程`)
    showQuickAdd.value = false
    loadSchedule()
    if (filterForm.classId) {
      loadAvailableCourses(filterForm.classId)
    } else {
      loadAvailableCourses()
    }
    
  } catch (error) {
    console.error('批量添加课程失败:', error)
    ElMessage.error(error.message || '批量添加课程失败')
  } finally {
    quickAddLoading.value = false
  }
}

const editCourse = (course) => {
  Object.assign(editCourseForm, { ...course })
  
  if (!isCurrentUserCourse(course)) {
    editCourseForm.isReadOnly = true
  } else {
    editCourseForm.isReadOnly = false
  }
  
  showEditDialog.value = true
}

const removeCourse = async (course) => {
  if (!isCurrentUserCourse(course)) {
    ElMessage.warning('您只能删除自己的课程')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定删除此课程吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await scheduleApi.deleteCourseFromSchedule(course.id)
    if (response.code === 200) {
      ElMessage.success('删除课程成功')
      loadSchedule()
      if (filterForm.classId) {
        loadAvailableCourses(filterForm.classId)
      } else {
        loadAvailableCourses()
      }
    } else {
      ElMessage.error(response.message || '删除课程失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

// 其他辅助方法
const getDayName = (dayValue) => {
  const day = weekDays.find(d => d.value === dayValue)
  return day ? day.label : ''
}

const getTimeSlotName = (timeSlot) => {
  const slot = timeSlots.value.find(s => s.timeSlot === timeSlot)
  return slot ? `第${timeSlot}节` : ''
}

const getTimeSlotDisplay = (timeSlot) => {
  const slot = timeSlots.value.find(s => s.timeSlot === timeSlot)
  return slot ? `第${timeSlot}节 (${slot.startTime}-${slot.endTime})` : ''
}

const getDetailedTimeDisplay = (timeSlot) => {
  const slot = timeSlots.value.find(s => s.timeSlot === timeSlot)
  return slot ? `${slot.startTime}-${slot.endTime}` : ''
}

const onClassChange = () => {
  console.log('选中的班级ID:', addForm.classId)
  
  const selectedClass = teacherClasses.value.find(c => c.id === addForm.classId)
  if (selectedClass) {
    addForm.className = selectedClass.name
  }
  
  addForm.courseId = null
  
  if (addFormRef.value) {
    addFormRef.value.clearValidate('courseId')
  }
  
  if (addForm.classId) {
    console.log('重新加载班级课程，班级ID:', addForm.classId)
    loadAvailableCourses(addForm.classId)
  }
}

const onQuickAddClassChange = () => {
  console.log('快速添加 - 选中的班级ID:', quickAddForm.classId)
  
  quickAddForm.courseId = null
  
  if (quickAddFormRef.value) {
    quickAddFormRef.value.clearValidate('courseId')
  }
  
  if (quickAddForm.classId) {
    loadAvailableCourses(quickAddForm.classId)
  }
}

const viewCourseDetails = (course) => {
  if (course) {
    editCourse(course)
  }
}

const onFilterChange = () => {
  loadSchedule()
}

const getSelectedClassName = () => {
  const selectedClass = teacherClasses.value.find(c => c.id === filterForm.classId)
  return selectedClass ? selectedClass.name : '所有班级'
}

const handleDragStart = (event, course) => {
  if (!isCurrentUserCourse(course)) {
    event.preventDefault()
    ElMessage.warning('只能拖拽自己的课程')
    return
  }
  
  if (filterForm.classId && course.classId !== filterForm.classId) {
    event.preventDefault()
    ElMessage.warning('只能拖拽当前班级的课程')
    return
  }
  
  isDragging.value = true
  draggedCourse.value = course
  event.dataTransfer.setData('text/plain', JSON.stringify(course))
  event.dataTransfer.effectAllowed = 'move'
  
  event.target.classList.add('dragging')
}

const handleDragEnd = (event) => {
  isDragging.value = false
  draggedCourse.value = null
  
  event.target.classList.remove('dragging')
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

const handleDrop = async (event, timeSlot, dayOfWeek) => {
  event.preventDefault()
  
  if (!draggedCourse.value) return
  
  const course = draggedCourse.value
  
  if (course.timeSlot === timeSlot && course.dayOfWeek === dayOfWeek) {
    isDragging.value = false
    draggedCourse.value = null
    return
  }
  
  try {
    const hasConflict = await checkDropConflict(timeSlot, dayOfWeek, course)
    if (hasConflict) {
      ElMessage.warning('目标时间段已有课程，无法移动')
      isDragging.value = false
      draggedCourse.value = null
      return
    }
    
    await moveCourse(course, timeSlot, dayOfWeek)
    
    ElMessage.success('课程移动成功')
    
    await loadSchedule()
    
  } catch (error) {
    console.error('移动课程失败:', error)
    ElMessage.error(error.message || '移动课程失败')
  } finally {
    isDragging.value = false
    draggedCourse.value = null
  }
}

const checkDropConflict = async (timeSlot, dayOfWeek, draggedCourse) => {
  try {
    const response = await scheduleApi.checkTimeConflict(
      filterForm.academicYear,
      filterForm.weekNumber,
      dayOfWeek,
      timeSlot,
      draggedCourse.classId
    )
    
    return response.code === 200 && response.data === true
  } catch (error) {
    console.error('检查冲突失败:', error)
    return true
  }
}

const moveCourse = async (course, newTimeSlot, newDayOfWeek) => {
  try {
    const updateData = {
      academicYear: course.academicYear,
      weekNumber: course.weekNumber,
      dayOfWeek: newDayOfWeek,
      timeSlot: newTimeSlot,
      classId: course.classId,
      className: course.className
    }
    
    const response = await scheduleApi.updateSchedule(course.id, updateData)
    
    if (response.code !== 200) {
      throw new Error(response.message || '更新课程失败')
    }
    
    return response
  } catch (error) {
    throw error
  }
}

// 生命周期钩子
onMounted(() => {
  initializeData()
})

onBeforeUnmount(() => {
  saveViewPosition()
})
</script>

<style scoped>
.schedule-management {
  padding: 20px;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.schedule-grid-container {
  overflow-x: auto;
}

.schedule-grid {
  min-width: 1200px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.grid-header {
  display: grid;
  grid-template-columns: 150px repeat(7, 1fr);
  background: #f5f7fa;
  border-bottom: 2px solid #e4e7ed;
}

.time-header,
.day-header {
  padding: 15px 10px;
  font-weight: bold;
  text-align: center;
  border-right: 1px solid #e4e7ed;
  color: #303133;
}

.grid-row {
  display: grid;
  grid-template-columns: 150px repeat(7, 1fr);
  border-bottom: 1px solid #e4e7ed;
}

.time-cell {
  padding: 15px 10px;
  background: #fafbfc;
  border-right: 1px solid #e4e7ed;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.time-slot-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.time-range {
  font-size: 12px;
  color: #909399;
  margin-bottom: 3px;
}

.time-period {
  font-size: 10px;
  color: #c0c4cc;
}

.course-cell {
  position: relative;
  min-height: 120px;
  border-right: 1px solid #e4e7ed;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.course-cell:hover {
  background-color: #f0f9ff;
}

.course-cell.has-course {
  background-color: #e3f2fd;
}

.course-cell.has-other-class {
  background-color: #f5f5f5;
  opacity: 0.7;
}

.course-cell.disabled {
  cursor: not-allowed;
  position: relative;
}

.course-cell.disabled:hover {
  background-color: #f5f5f5 !important;
}

.course-cell.drag-over {
  background-color: #e8f5e8 !important;
  border: 2px dashed #67c23a;
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.course-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
  cursor: move;
  transition: all 0.3s ease;
  border-radius: 6px;
}

.course-content[draggable="false"] {
  cursor: default;
  opacity: 0.8;
}

.course-content:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.course-content[draggable="false"]:hover {
  transform: none;
  box-shadow: none;
}

.course-content.dragging {
  opacity: 0.7;
  transform: rotate(5deg) scale(1.05);
  z-index: 1000;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.drag-handle {
  position: absolute;
  top: 2px;
  right: 2px;
  color: #c0c4cc;
  font-size: 12px;
  cursor: move;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.course-content:hover .drag-handle,
.course-item:hover .drag-handle {
  opacity: 1;
}

.course-name {
  font-weight: bold;
  color: #1976d2;
  font-size: 13px;
  margin-bottom: 4px;
}

.course-time {
  font-size: 11px;
  color: #666;
  margin-bottom: 2px;
}

.course-teacher {
  font-size: 11px;
  color: #666;
  margin-bottom: 2px;
}

.course-class {
  font-size: 10px;
  color: #999;
  margin-bottom: 4px;
}

.course-actions {
  display: flex;
  gap: 4px;
  margin-top: auto;
}

.empty-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 12px;
}

.add-hint {
  text-align: center;
}

.no-week-selected {
  text-align: center;
  padding: 40px;
}

@media (max-width: 1200px) {
  .schedule-grid {
    min-width: 1000px;
  }
}

.multiple-courses {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px;
}

.course-item {
  border-radius: 4px;
  padding: 6px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  cursor: move;
  transition: all 0.3s ease;
  position: relative;
}

.course-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.course-item.dragging {
  opacity: 0.7;
  transform: rotate(3deg) scale(1.05);
  z-index: 1000;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

.course-item .course-name {
  font-weight: bold;
  color: #1976d2;
  font-size: 12px;
  margin-bottom: 2px;
}

.course-item .course-class {
  font-size: 10px;
  color: #666;
  margin-bottom: 4px;
}

.course-item .course-actions {
  display: flex;
  gap: 2px;
  justify-content: flex-end;
}

.course-item .course-actions .el-button {
  padding: 2px;
  min-height: auto;
}

.class-legend {
  margin-top: 15px;
  padding: 15px;
  background: #f0f2f5;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.legend-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  font-size: 14px;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.legend-text {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.other-class-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px;
  position: relative;
}

.other-course-item {
  border-radius: 4px;
  padding: 6px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  opacity: 0.6;
  pointer-events: none;
}

.other-course-item .course-name {
  font-weight: bold;
  color: #1976d2;
  font-size: 12px;
  margin-bottom: 2px;
}

.other-course-item .course-class {
  font-size: 10px;
  color: #666;
  margin-bottom: 2px;
}

.other-course-item .course-teacher {
  font-size: 10px;
  color: #666;
}

.disabled-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(1px);
}

.disabled-text {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.drop-hint {
  text-align: center;
  color: #67c23a;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 500;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 0.6; transform: scale(1); }
  50% { opacity: 1; transform: scale(1.05); }
  100% { opacity: 0.6; transform: scale(1); }
}

/* 其他教师的课程样式 */
.other-teacher-course {
  background-color: #f5f5f5 !important;
  opacity: 0.7;
  cursor: pointer !important;
  pointer-events: auto;
  position: relative;
}

.other-teacher-course .course-name {
  color: #909399 !important;
}

.other-teacher-course .course-teacher,
.other-teacher-course .course-class,
.other-teacher-course .course-time {
  color: #c0c4cc !important;
}

.other-teacher-course:hover {
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  background-color: #eeeeee !important;
}

/* 只读标识样式 */
.readonly-indicator {
  position: absolute;
  top: 2px;
  right: 2px;
  color: #c0c4cc;
  font-size: 12px;
  opacity: 0.8;
}

/* 确保其他教师的课程不能拖拽 */
.other-teacher-course[draggable="false"] {
  cursor: not-allowed !important;
}

/* 多课程显示时的其他教师课程样式 */
.course-item.other-teacher-course {
  background-color: #f5f5f5 !important;
  opacity: 0.7;
  cursor: pointer !important;
  pointer-events: auto;
}

.course-item.other-teacher-course:hover {
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  background-color: #eeeeee !important;
}

.course-item.other-teacher-course .course-name {
  color: #909399 !important;
}

.course-item.other-teacher-course .course-class,
.course-item.other-teacher-course .course-teacher {
  color: #c0c4cc !important;
}
</style> 